<template>
  <div class="container mx-auto px-4 py-8">
    <!-- 时间显示区域 -->
    <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
      <div class="flex flex-col md:flex-row justify-between items-center">
        <div class="flex flex-col mb-6 md:mb-0">
          <div class="text-gray-600 text-xl">Your Area Now Time</div>
          <div class="text-6xl font-bold text-[#41A5E0] transition-all hover:scale-105">
            {{ dataObj.nowtime }}
          </div>
        </div>
        <Clock class="w-48 h-48" />
      </div>
    </div>

    <!-- 位置信息区域 -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
      <div class="bg-white rounded-lg shadow-lg p-6">
        <h2 class="text-2xl font-bold mb-4 text-gray-800">Location Info</h2>
        <div class="space-y-4">
          <div class="flex items-center">
            <div class="text-gray-600 w-40">Public IP</div>
            <div class="text-xl text-[#41A5E0]">{{ dataObj.ip || 'Loading...' }}</div>
          </div>
          <div class="flex items-center">
            <div class="text-gray-600 w-40">Address</div>
            <div class="text-xl text-[#41A5E0]">{{ dataObj.address || 'Loading...' }}</div>
          </div>
          <div class="flex items-center">
            <div class="text-gray-600 w-40">Coordinates</div>
            <div class="text-xl text-[#41A5E0]">
              {{ dataObj.latitude }}, {{ dataObj.longitude }}
            </div>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-lg shadow-lg p-6">
        <h2 class="text-2xl font-bold mb-4 text-gray-800">Time Info</h2>
        <div class="space-y-4">
          <div class="flex items-center">
            <div class="text-gray-600 w-40">Timezone</div>
            <div class="text-xl text-[#41A5E0]">{{ dataObj.timezone }}</div>
          </div>
          <div class="flex items-center">
            <div class="text-gray-600 w-40">UTC Offset</div>
            <div class="text-xl text-[#41A5E0]">{{ dataObj.UTCOffset }}</div>
          </div>
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <div class="text-gray-600 w-40">Sunrise</div>
              <div class="text-xl text-[#41A5E0]">{{ dataObj.sunrise }}</div>
            </div>
            <div class="flex items-center ml-4">
              <div class="text-gray-600 w-40">Sunset</div>
              <div class="text-xl text-[#41A5E0]">{{ dataObj.sunset }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 国家信息区域 -->
    <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
      <h2 class="text-2xl font-bold mb-4 text-gray-800">Country Info</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div class="flex items-center">
          <div class="text-gray-600 w-40">Country</div>
          <div class="text-xl text-[#41A5E0]">{{ dataObj.country }}</div>
        </div>
        <div class="flex items-center">
          <div class="text-gray-600 w-40">Capital</div>
          <div class="text-xl text-[#41A5E0]">{{ dataObj.capital }}</div>
        </div>
        <div class="flex items-center">
          <div class="text-gray-600 w-40">Currency</div>
          <div class="text-xl text-[#41A5E0]">{{ dataObj.currency }}</div>
        </div>
        <div class="flex items-center">
          <div class="text-gray-600 w-40">Country Code</div>
          <div class="text-xl text-[#41A5E0]">{{ dataObj.countryCode }}</div>
        </div>
        <div class="flex items-center">
          <div class="text-gray-600 w-40">Calling Code</div>
          <div class="text-xl text-[#41A5E0]">{{ dataObj.callingCode }}</div>
        </div>
      </div>
    </div>

    <!-- 邻近国家时区表格 -->
    <div class="bg-white rounded-lg shadow-lg p-6">
      <h2 class="text-2xl font-bold mb-4 text-gray-800">Neighboring Countries</h2>
      <el-table
        :data="dataObj.dataList"
        border
        stripe
        class="w-full"
        :header-cell-style="{ background: '#f8fafc', color: '#1e293b' }"
      >
        <el-table-column label="Country" prop="country"></el-table-column>
        <el-table-column label="UTC Offset" prop="UTCOffset"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive } from 'vue';
import { ElDescriptions, ElDescriptionsItem, ElTable, ElTableColumn, ElLoading } from 'element-plus';
import Clock from './Clock.vue'
import 'element-plus/theme-chalk/el-loading.css';

const dataObj = reactive({
  ip: '获取ip地址中...',
  address: '',
  nowtime: '',
  timezone: '',
  UTCOffset: '',
  dst: false,
  sunrise: '',
  sunset: '',
  country: '',
  capital: '',
  callingCode: '',
  latitude: '',
  longitude: '',
  currency: '',
  countryCode: '',
  dataList: [{
    country: 'Japan',
    UTCOffset: '+9 hours'
  }, {
    country: 'Korea',
    UTCOffset: '+9 hours'
  }, {
    country: 'Mongolia',
    UTCOffset: '+8 hours'
  }, {
    country: 'Vietnam',
    UTCOffset: '+7 hours'
  }, {
    country: 'Thailand',
    UTCOffset: '+7 hours'
  }, {
    country: 'Myanmar',
    UTCOffset: '+6.5 hours'
  }, {
    country: 'India',
    UTCOffset: '+5.5 hours'
  }, {
    country: 'Kazakhstan',
    UTCOffset: '+6 hours'
  }, {
    country: 'Russia (Moscow)',
    UTCOffset: '+3 hours'
  }, {
    country: 'Pakistan',
    UTCOffset: '+5 hours'
  }]
})

const getLocationInfo = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading location information...',
    background: 'rgba(255, 255, 255, 0.7)',
  });

  try {
    timeOutNow();
    getLocation();

    // 获取IP地址和地理位置
    const ipResponse = await fetch('https://ipapi.co/json/');
    const ipData = await ipResponse.json();
    const { ip, city, region, country_name, latitude, longitude, country_capital, country_calling_code, currency, country_code } = ipData;
    dataObj.ip = ip;
    dataObj.address = city + ' ' + region + ' ' + country_name;
    dataObj.capital = country_capital;
    dataObj.country = country_name;
    dataObj.callingCode = country_calling_code;
    dataObj.latitude = latitude;
    dataObj.longitude = longitude;
    dataObj.currency = currency;
    dataObj.countryCode = country_code;

    // 获取时区信息
    const timezoneResponse = await fetch('https://worldtimeapi.org/api/ip');
    const timezoneData = await timezoneResponse.json();
    const { datetime, timezone, utc_offset, dst } = timezoneData;
    dataObj.timezone = timezone;
    dataObj.UTCOffset = utc_offset;
    dataObj.dst = dst;

    // 获取日出日落时间
    const sunriseSunsetRes = await fetch('https://api.sunrise-sunset.org/json?formatted=0&lat=' + latitude + '&lng=' + longitude);
    const sunriseSunsetData = await sunriseSunsetRes.json();
    const { sunrise, sunset } = sunriseSunsetData.results;
    dataObj.sunrise = formatTime(sunrise);
    dataObj.sunset = formatTime(sunset);
  } catch (error) {
    console.error('Error fetching data:', error);
  } finally {
    loading.close();
  }
}

const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleTimeString();
}

const timeOutNow = () => {
  const date = new Date();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  const xz = date.getDay(); // 获取星期
  dataObj.nowtime = weekStr(xz) + ' ' +
    String(hour).padStart(2, '0') + ':' + String(minute).padStart(2, '0') + ':' + String(second).padStart(2, '0');

}

const weekStr = (type: number) => {
  switch (type) {
    case 0: return 'Sunday';
    case 1: return 'Monday';
    case 2: return 'Tuesday';
    case 3: return 'Wednesday';
    case 4: return 'Thursday';
    case 5: return 'Friday';
    case 6: return 'Saturday';
    default: return 'Sunday';
  }
}

function getLocation() {
  console.log(navigator.geolocation);
  if (navigator.geolocation) {
    console.log("geolocation supported");
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  } else {

  }
}

function showPosition(position) {
  console.log("position: " + position);
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;
  console.log("Latitude: " + latitude + ", Longitude: " + longitude);
}

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      break;
    case error.POSITION_UNAVAILABLE:
      break;
    case error.TIMEOUT:
      break;
    case error.UNKNOWN_ERROR:
      break;
  }
}

onMounted(() => {
  setInterval(() => {
    timeOutNow();
  }, 1000);
  getLocationInfo();
})
</script>